package com.lengxf.pay.common.sign.service;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;

import java.nio.charset.Charset;
import java.util.Base64;

public class RsaSignService implements SignService {

    private final static SignAlgorithm SIGN_ALGORITHM = SignAlgorithm.SHA1withRSA;

    @Override
    public String sign(String text, String keyPrivate, String characterEncoding) {
        String charset = StrUtil.isBlank(characterEncoding) ? "UTF-8" : characterEncoding;
        Sign sign = SecureUtil.sign(SIGN_ALGORITHM, keyPrivate, null);
        byte[] bytes = sign.sign(text, CharsetUtil.charset(charset));
        return Base64.getEncoder().encodeToString(bytes);
    }

    @Override
    public Boolean verify(String text, String sign, String keyPublic, String characterEncoding) {
        return SecureUtil.sign(SIGN_ALGORITHM, null, keyPublic)
                .verify(StrUtil.bytes(text, Charset.forName(characterEncoding)),
                        Base64.getDecoder().decode(sign));
    }

}
